package com.api.rc.lobby.message;

import com.alibaba.fastjson.JSON;
import com.api.rc.lobby.domain.LobbyRoom;
import com.api.rc.lobby.domain.LobbyTeam;
import com.api.rc.lobby.vo.LobbyPlayerVo;
import com.api.rc.lobby.vo.LobbyTeamVo;
import org.springframework.web.socket.TextMessage;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author RenQiang
 * @date 2021/7/17
 */
public class MessageGenerator {

    /**
     * 生成心跳消息
     *
     * @return
     */
    public static TextMessage genHeartBeatMsg() {
        LobbyMessage<Long> lobbyMessage = new LobbyMessage<>(LobbyEvent.HEART_BEAT, System.currentTimeMillis());
        return new TextMessage(JSON.toJSONString(lobbyMessage));
    }

    /**
     * 生成系统消息
     *
     * @param event
     * @param message
     * @return
     */
    public static TextMessage genSystemMessage(LobbyEvent event, String message) {
        LobbyMessage<Void> lobbyMessage = new LobbyMessage<>(event, message);
        return new TextMessage(JSON.toJSONString(lobbyMessage));
    }

    /**
     * 生成房间详情消息
     *
     * @param lobbyRoom
     * @return
     */
    public static TextMessage genRoomDetailMessage(LobbyRoom lobbyRoom) {
        Map<Integer, LobbyTeam> teamMap = lobbyRoom.getTeamMap();
        List<LobbyTeamVo> roomTeams = teamMap.values().stream()
                .map(lobbyTeam -> convertLobbyTeam(lobbyRoom.getRoomId(), lobbyTeam))
                .collect(Collectors.toList());
        LobbyMessage<List<LobbyTeamVo>> roomDetail = new LobbyMessage<>(LobbyEvent.SERVER_ROOM_DETAIL, roomTeams);
        return new TextMessage(JSON.toJSONString(roomDetail));
    }

    /**
     * 生成队伍详情消息
     *
     * @param roomId
     * @param lobbyTeam
     * @return
     */
    public static TextMessage genTeamDetailMessage(Long roomId, LobbyTeam lobbyTeam) {
        LobbyTeamVo lobbyTeamVo = convertLobbyTeam(roomId, lobbyTeam);
        LobbyMessage<LobbyTeamVo> teamDetail = new LobbyMessage<>(LobbyEvent.SERVER_TEAM_DETAIL, lobbyTeamVo);
        return new TextMessage(JSON.toJSONString(teamDetail));
    }

    private static LobbyTeamVo convertLobbyTeam(Long roomId, LobbyTeam lobbyTeam) {
        LobbyTeamVo lobbyTeamVo = new LobbyTeamVo();
        lobbyTeamVo.setRoomId(roomId);
        lobbyTeamVo.setNo(lobbyTeam.getNo());
        lobbyTeamVo.setMaxMembers(lobbyTeam.getMaxMembers());
        lobbyTeamVo.setMembers(lobbyTeam.getMemberMap().values().stream()
                .map(lobbyPlayer -> {
                    LobbyPlayerVo lobbyPlayerVo = new LobbyPlayerVo();
                    lobbyPlayerVo.setUserInfo(lobbyPlayer.getUserInfo());
                    lobbyPlayerVo.setIsReady(lobbyPlayer.isReady());
                    return lobbyPlayerVo;
                }).collect(Collectors.toList()));
        return lobbyTeamVo;
    }
}
